
package com.tansun.tandata.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.ctc.wstx.dtd.TokenModel;
import com.tansun.tandata.utils.*;
import com.tansun.tandata.vo.LdapUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tansun.tandata.service.UserService;
import com.tansun.tandata.vo.req.UserChangePwdVO;
import com.tansun.tandata.vo.req.UserVO;
import com.tansun.tandata.vo.res.UserInfoVO;
import com.tansun.tandata.vo.res.UserRoleByLoginNameVO;
import com.tansun.tandata.vo.res.UserRoleVO;
import com.tansun.tjmas.cloud.base.redis.common.RedisConstant;
import com.tansun.tjmas.cloud.base.redis.utils.RedisUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @Description 用户信息控制器

 * @CreateDate 20200426
 * @author shenxiaodong
 * @Version v1.0
 *
 */
@Api(value = "用户接口")
@RestController
@RequestMapping(value = "/sys/user")
public class UserController extends ParentController{

	@Autowired
	private UserService userService;

	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private LocaleMessage localeMessage;

	@ApiOperation(value="模糊查询用户信息", notes="根据关键字获取用户信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "keywords", value = "关键字", dataType = "String", defaultValue = ""),
			@ApiImplicitParam(name = "status", value = "类型", required = true, defaultValue = "2", dataType = "int"),
			@ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "int"),
			@ApiImplicitParam(name = "limit", value = "显示数量", required = true, dataType = "int")
	})
	@RequestMapping(value = "/getUserByKey", method=RequestMethod.GET)
	public ResponseBase<Map<String, Object>>  getUserByKey(@RequestParam(name = "keywords", defaultValue = "") String keywords, @RequestParam(name = "status", defaultValue = "2") int status,
														   @RequestParam("page") int page, @RequestParam("limit") int limit) {
		Map<String, Object> data = new HashMap<>();
		List<UserRoleVO> users;
		try {
			Page<Object> pageInfo = PageHelper.startPage(page, limit, true);
			users = userService.getUserByKey(keywords, status);
			data.put("total", pageInfo.getTotal());
			data.put("data", users);
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
		}
		return setResultSuccess(data);

	}

	@ApiOperation(value="查询所有用户信息", notes="查询所有用户信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "int"),
			@ApiImplicitParam(name = "limit", value = "显示数量", required = true, dataType = "int")
	})
	@RequestMapping(value = "/selectAllUser", method=RequestMethod.GET)
	public ResponseBase  selectAllUser(@RequestParam("page") int page, @RequestParam("limit") int limit) {
		Map<String, Object> data = new HashMap<>();
		try {
			Page<Object> pageInfo = PageHelper.startPage(page, limit, true);
			List<UserRoleVO> users = userService.selectAllUser();
			data.put("total", pageInfo.getTotal());
			data.put("data", users);
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
		}
		return setResultSuccess(data);
	}

	@ApiOperation(value="用户基本信息插入", notes="用户基本信息插入")
	@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public ResponseBase saveUser(@Valid @RequestBody UserVO userVO, BindingResult bindingResult ) {
		// 验证实体输入参数
		ResponseBase validResult = validateField(bindingResult);
		if (validResult != null) {
			return validResult;
		}
		//存在性验证，姓名验证
		int count = userService.getUserByLoginNameOrPhone(userVO.getLoginName(), userVO.getUserPhone());
		if (count > Constants.CHAR_INT_ZERO) {
			return setResult(Constants.HTTP_RES_CODE_402,localeMessage.getMessage("sys.common.user.name.phone.isExist"),null);
		}
		try {
			userService.saveUser(userVO);
		} catch (RuntimeException e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
		}
		return setResultSuccess(userVO);
	}

	@ApiOperation(value="修改用户基本信息", notes="修改用户基本信息")
	@RequestMapping(value="updateUser", method=RequestMethod.POST)
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResponseBase updateUser(@Valid @RequestBody UserVO userVO, BindingResult bindingResult){
		// 验证实体输入参数
		ResponseBase validResult = validateField(bindingResult);
		if (validResult != null) {
			return validResult;
		}
		//存在性验证，姓名验证
		UserRoleVO check = userService.selectUserById(userVO.getUserCode());
		if(!check.getUserName().equals(userVO.getUserName())) {
			int count = userService.getUserByName(userVO.getUserName());
			if (count > Constants.CHAR_INT_ZERO) {
				return setResult(Constants.HTTP_RES_CODE_402,localeMessage.getMessage("sys.common.user.name.isExist"),null);
			}
		}
		try {
			userService.updateUser(userVO);
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
		}
		return setResultSuccess(userVO);
	}

	@ApiOperation(value="删除用户基本信息", notes="删除用户基本信息")
	@ApiImplicitParam(name = "userCode", value = "用户编号", required = true, dataType = "String")
	@RequestMapping(value="deleteUser", method=RequestMethod.GET)
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResponseBase deleteUser(@RequestParam("userCode") String userCode){
		try {
			userService.deleteUser(userCode);
		} catch (Exception e) {
			e.printStackTrace();
			//系统错误
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
		}
		return setResultSuccess(localeMessage.getMessage("sys.user.deleteSuccess"));
	}

	@ApiOperation(value="修改用户类型", notes="修改用户类型")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userCode", value = "用户编号", required = true, dataType = "String"),
			@ApiImplicitParam(name = "status", value = "类型", required = true, dataType = "String")
	})
	@RequestMapping(value="updateUserType",method=RequestMethod.GET)
	public ResponseBase updateUserType(@RequestParam("userCode") String userCode ,@RequestParam("status") String status){
		try {
			userService.updateUserType(userCode, status);
			return setResultSuccessSetMsg(localeMessage.getMessage("sys.user.updateSuccess"));
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
		}
	}

	@ApiOperation(value="根据用户登录名称查询用户基本信息", notes="根据用户登录名称查询用户基本信息")
	@ApiImplicitParam(name = "loginName", value = "登录名称", required = true, dataType = "String")
	@RequestMapping(value="/getUserAndRoleInfoByLoginName", method=RequestMethod.GET)
	public ResponseBase getUserAndRoleInfoByLoginName(@RequestParam("loginName") String loginName){
		try {
			UserRoleByLoginNameVO userRoleByLoginNameVO = userService.selectUserAndRoleInfoByLoginName(loginName);
			return setResultSuccess(JSON.toJSONString(userRoleByLoginNameVO));
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"),null); //系统错误
		}
	}

	@ApiOperation(value="用户登录以后返回用户基本信息", notes="用户登录以后返回用户基本信息")
	@RequestMapping(value="/getUserInfoAfterLogin", method=RequestMethod.GET)
	public ResponseBase<UserInfoVO> getUserInfoAfterLogin(HttpServletRequest request){
		try {
			//根据登录名查询用户信息
			String redisId = request.getHeader(RedisConstant.REDIS_ID);
			HashMap<String, Object> userMap = (HashMap<String, Object>) redisUtils.get(redisId);
			UserInfoVO usVO = JSONObject.parseObject(userMap.get("userInfo").toString(), UserInfoVO.class);

			UserInfoVO userInfoVO = userService.getUserInfoAfterLogin(usVO.getLoginName());
			return setResultSuccess(userInfoVO);
		} catch (Exception e) {
			e.printStackTrace();
			//系统错误
			return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null);
		}
	}

	@ApiOperation(value="修改用户密码", notes="修改用户密码")
	@RequestMapping(value="updateUserPwd", method=RequestMethod.POST)
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResponseBase updateUserPwd(@Valid @RequestBody UserChangePwdVO userChangePwdVO, BindingResult bindingResult){
		// 验证实体输入参数
		ResponseBase validResult = validateField(bindingResult);
		if (validResult != null) {
			return validResult;
		}
		//原密码正确性性验证，密码验证
		UserRoleVO check = userService.selectUserById(userChangePwdVO.getUserCode());
		if(!check.getPassword().equals(userChangePwdVO.getOldPassword())) {
			return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("sys.user.password.error"), null);
		}
		try {
			userService.updateUserPwd(userChangePwdVO);
			return setResultSuccess(userChangePwdVO);
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
		}
	}

	@ApiOperation(value="将所有用户信息缓存到redis", notes="将所有用户信息缓存到redis")
	@RequestMapping(value="/getAllUserInfo2Redis", method=RequestMethod.GET)
	public ResponseBase getAllUserInfo2Redis(){
		try {
			List<UserRoleVO> users = userService.selectAllUser();
			for (UserRoleVO user : users) {
				redisUtils.set(Constants.USER_REDIS + user.getUserCode(), user.getUserName());
			}
			return setResultSuccess(localeMessage.getMessage("sys.user.put.redis.success"));
		} catch (Exception e) {
			e.printStackTrace();
			//系统错误
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
		}
	}

	@ApiOperation(value="修改用户对应的机构", notes="关联用户和机构")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userCode", value = "用户编码", required = true, dataType = "String"),
			@ApiImplicitParam(name = "orgCode", value = "机构编码", required = true, dataType = "String")
	})
	@RequestMapping(value="updateOrgCodeByUserCode", method=RequestMethod.GET)
	public ResponseBase updateOrgCodeByUser(@RequestParam("userCode") String userCode ,@RequestParam("orgCode") String orgCode){
		try {
			userService.updateOrgCodeByUser(userCode, orgCode);
			return setResultSuccess(localeMessage.getMessage("sys.user.set.org.success"));
		} catch (Exception e) {
			return sysError(e);
		}
	}
	@ApiOperation(value="用户登出", notes="关联用户和机构")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username", value = "用户登录名", required = false, dataType = "String"),
	})
	@RequestMapping(value="logout", method=RequestMethod.POST)
	public ResponseBase logout( String username,HttpServletRequest request){
		try {
			//删除用户redise信息
			String redisId = request.getHeader(RedisConstant.REDIS_ID);
			if(!StringUtil.isEmpty(redisId)){
				redisUtils.delete(redisId);
			}
			return setResultSuccess(localeMessage.getMessage("sys.user.set.org.success"));
		} catch (Exception e) {
			return sysError(e);
		}
	}
	@ApiOperation(value="同步域账号到提数系统账号", notes="同步域账号到提数系统账号")
	@RequestMapping(value="ldapUserToSysUser", method=RequestMethod.POST)
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResponseBase ldapUserToSysUser(@RequestBody LdapUser ldapUser){
		try {
			userService.ldapUserToSysUser(ldapUser);
			return setResultSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
		}
	}
	@ApiOperation(value="根据登录名锁定系统中的域账号", notes="根据登录名锁定系统中的域账号")
	@ApiImplicitParam(name = "loginName", value = "登录名称", required = true, dataType = "String")
	@RequestMapping(value="/lockLdapUserByLoginName", method=RequestMethod.GET)
	public ResponseBase lockLdapUserByLoginName(@RequestParam("loginName") String loginName){
		try {
			userService.lockLdapUserByLoginName(loginName);
			return setResultSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"),null); //系统错误
		}
	}

}